<?php

namespace App\Models;

use Illuminate\Support\Str;

class Order extends Model
{
    protected $guarded = [
        'user_id',
    ];

    protected $dates = [
        'completed_at',
        'closed_at',
    ];

    protected $casts = [
        'closed'    => 'boolean',
        'completed' => 'boolean',
        'address'   => 'json',
    ];

    protected $appends = [
        'status',
        'order_time_date',
    ];

    public static $orderTimeMap = [
        1   => '今天-随时(9:00-18:00)',
        2   => '明天-上午(9:00-12:00)',
        3   => '明天-下午(12:00-18:00)',
    ];

    public static $orderStatusMap = [
        0   => '全部',
        1   => '呼叫中',
        2   => '已完成',
        3   => '已取消',
    ];


    // 监听器
    protected static function boot()
    {
        parent::boot();
        // 监听模型创建事件，在写入数据库之前触发
        static::creating(function ($model) {
            // 如果模型的 no 字段为空
            if (!$model->no) {
                // 调用 findAvailableNo 生成订单流水号
                $model->no = static::findAvailableNo();
                // 如果生成失败，则终止创建订单
                if (!$model->no) {
                    return false;
                }
            }
        });
    }


    /**
     * 关联模型
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }


    /**
     * 访问器
     */
    public function getStatusAttribute()
    {
        if($this->closed){
            $status = 3;
        }elseif($this->completed){
            $status = 2;
        }else{
            $status = 1;
        }

        return $status;
    }

    public function getOrderTimeDateAttribute()
    {
        switch ($this->order_time) {
            case 2:
            case 3:
                $date = $this->created_at->addDay(1)->toDateString();
                break;

            default:
                $date = $this->created_at->toDateString();
                break;
        }

        return $date . '-' . Str::after(self::$orderTimeMap[$this->order_time], '-');
    }


    /**
     * 查询作用域
     */
    public function scopeOrderStatus($query, $status = 0)
    {
        switch ($status) {
            case 1: // 呼叫中
            $query->closedStatus(false)
                ->completedStatus(false);
                break;

            case 2: // 已完成
                $query->completedStatus();
                break;

            case 3: // 已取消
                $query->closedStatus();
                break;

            default:

                break;
        }

        return $query;
    }

    public function scopeClosedStatus($query, $status = true)
    {
        return $query->where('closed', $status);
    }

    public function scopeCompletedStatus($query, $status = true)
    {
        return $query->where('completed', $status);
    }


    /**
     * 自定义方法
     */
    public static function findAvailableNo()
    {
        // 订单流水号前缀
        $prefix = date('YmdHis');
        for ($i = 0; $i < 10; $i++) {
            // 随机生成 6 位的数字
            $no = $prefix.str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
            // 判断是否已经存在
            if (!static::query()->where('no', $no)->exists()) {
                return $no;
            }
        }
        Log::warning('find order no failed');

        return false;
    }
}
